//
//  YJStatusPictureView.swift
//  YJWeiBo
//
//  Created by Jim1024 on 2017/1/17.
//  Copyright © 2017年 Jim1024. All rights reserved.
//

import UIKit
import Kingfisher

class YJStatusPictureView: UICollectionView {

    fileprivate let kReuseIdentifier = "ReuseIdentifier"
    
    fileprivate let layout = UICollectionViewFlowLayout()
    
    var pictureURLs: [URL]? {
        didSet {
            // 拿到需要显示的图片的数组后,根据图片的数量来计算配图需要的宽和高
            let size = calcViewSize()
            
            // 更新约束
            self.snp.updateConstraints { (make) in
                make.size.equalTo(size)
            }
            self.superview?.setNeedsLayout()
            
            // 当拿到pictureURLs后.来根据pictureURLs的数量重新设置
            self.reloadData()
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: self.layout)
        
        // 默认是true,如果一个控制器的view里面只有一个UIScrollView/子类,当点击状态栏scrollsToTop=true是可以滚动到顶部
        self.scrollsToTop = false
        
        self.dataSource = self
        self.register(YJStatusPictureViewCell.self, forCellWithReuseIdentifier: kReuseIdentifier)
        
        self.backgroundColor = UIColor.clear
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 根据图片的数量来计算配图需要的宽和高
    fileprivate func calcViewSize() -> CGSize {
        layout.itemSize = CGSize(width: YJStatusPictureCellWH, height: YJStatusPictureCellWH)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let count = pictureURLs?.count ?? 0
        
        if count == 0 {
            layout.itemSize = CGSize.zero
            return CGSize.zero
        }
        
        // 单图会按照图片 原始尺寸 显示
        if count == 1 {
            // 单张图片默认大小
            var imageSize = CGSize(width: 160, height: 120)
            let urlString = pictureURLs!.first!.absoluteString
            
            // 去本地获取对应图片的大小
            if let image = ImageCache.default.retrieveImageInDiskCache(forKey: urlString) {
                imageSize = image.size
            }
            if imageSize.width < 40 {
                imageSize.width = 40
            } else if imageSize.width > UIScreen.width * 0.5 {
                imageSize.width = UIScreen.width * 0.5
            }
            
            layout.itemSize = imageSize
            return imageSize
        }
        
        // 多张图片
        layout.minimumInteritemSpacing = YJStatusPictureMargin
        layout.minimumLineSpacing = YJStatusPictureMargin
        
        // 默认3列
        var column = YJStatusPictureMaxColumn
        
        if count == 2 || count == 4 {
            column = 2
        }
        
        // 计算总行数, 一定要注意:column是整数
        let row = (count + column - 1) / column
        
        // 计算宽度 cell的宽度 * 列数 + (列数 - 1) * cell之间的间距
        let width = YJStatusPictureCellWH * CGFloat(column) + CGFloat(column - 1) * YJStatusPictureMargin
        // 计算高度 cell的高度 * 行数 + (行数 - 1) * cell之间的间距
        let height = YJStatusPictureCellWH * CGFloat(row) + (CGFloat(row) - 1) * YJStatusPictureMargin
        
        return CGSize(width: width, height: height)
    }
}

// MARK: - collection view data source
extension YJStatusPictureView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kReuseIdentifier, for: indexPath) as! YJStatusPictureViewCell
        
        cell.imageURL = pictureURLs?[indexPath.item]
        
        return cell
    }
}


// MARK: - 自定义YJStatusPictureViewCell
class YJStatusPictureViewCell: UICollectionViewCell {
    
    fileprivate var imageURL: URL? {
        didSet {
            if let url = imageURL {
                bgImageView.kf.setImage(with: url)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initCustomView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func initCustomView() {
        contentView.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    fileprivate lazy var bgImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
}
